<?php

namespace App\Events;

use App\Models\StudentResult;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class ExamingEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $key;
    public $data;
    public $exam;
    public $result;

    /**
     * Create a new event instance.
     *
     * @param $key
     * @param $data
     * @param $exam
     */
    public function __construct($key, $data, $exam)
    {
        $this->key = $key;
        $this->data = $data;
        $this->exam = $exam;
        $this->getQuestions();
    }


    /**
     * 获取考试题目信息
     */
    public function getQuestions()
    {
        // 判断用户id是否存在
        if (array_key_exists('user_id', $this->data['data'])) {
            $data = StudentResult::query()
                ->where('examination_id', $this->key)
                ->where('user_id', $this->data['data']['user_id'])
                ->where('submit_type', 4)
                ->value('content');

            $this->handleQuestion($data);
        }
    }

    /**
     * 找到该事件应该在哪个频道播出.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('exam.' . $this->key);
    }

    /**
     * 处理考生填写数据
     *
     * @param $data
     */
    public function handleQuestion($data)
    {
        foreach ($data as &$datum) {
            if ($datum['id'] == $this->data['data']['question_id']) {
                $res = autoCorrect($this->data['data']);
                $datum['answer'] = $res['answer'];
                $datum['is_true'] = $res['is_true'];
                $datum['fraction'] = $res['fraction'];
            }
        }

        StudentResult::query()
            ->where('examination_id', $this->key)
            ->where('user_id', $this->data['data']['user_id'])
            ->where('submit_type', 4)
            ->update(['content' => $data]);
    }

    /**
     * 返回数据
     *
     * @return string[]
     */
    public function broadcastWith(): array
    {
        return ['message' => '考试结束'];
    }
}
